﻿using System;
using System.Windows.Forms;
using BLL.MaterialBLL;
using MDMUI.MaterialUI;
using Model;

namespace MDMUI
{
    public partial class MaterialManage : Form
    {
        private BLL.MaterialBLL.MaterialBLL _materialBLL = new BLL.MaterialBLL.MaterialBLL();
        private HistoryForm _historyForm;
        public MaterialManage()
        {
            InitializeComponent();
            this.Load += new System.EventHandler(this.MaterialManage_Load);
            this.Load += MaterialManage_Load;
            MaterialData.CellContentClick += MaterialData_CellContentClick;
            btnShowDeleted.Click += BtnShowDeleted_Click;
        }

        private void MaterialManage_Load(object sender, EventArgs e)
        {
            // 加载物料类型到 ComboBox1
            LoadMaterialTypes();

            // 加载所有材料到 DataGridView
            LoadMaterials();
        }

        private void LoadMaterialTypes()
        {
            List<string> materialTypes = _materialBLL.GetDistinctMaterialTypes();
            comboBox1.Items.Clear();
            comboBox1.Items.Add(""); // 添加空选项
            comboBox1.Items.AddRange(materialTypes.ToArray());
        }

        private void LoadDetailedTypes(string materialType)
        {
            // 清空前添加调试输出
            Console.WriteLine($"Loading detailed types for: {materialType}");

            comboBox2.Items.Clear();
            comboBox2.Items.Add("");

            try
            {
                List<string> detailedTypes = _materialBLL.GetDistinctDetailedTypes(materialType);

                // 验证是否获取到数据
                if (detailedTypes == null || detailedTypes.Count == 0)
                {
                    MessageBox.Show($"未找到 [{materialType}] 的详细类型");
                    return;
                }

                comboBox2.Items.AddRange(detailedTypes.ToArray());

                // 自动选择第一项（可选）
                if (comboBox2.Items.Count > 1) comboBox2.SelectedIndex = 1;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载详细类型失败: {ex.Message}");
            }
        }

        private void LoadMaterials()
        {
            List<Model.Material> materials = _materialBLL.GetAllMaterials();
            MaterialData.DataSource = materials; // 确保这里绑定的是 List<Model.Material>
            SetDataGridViewColumnHeaders();
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox1.SelectedItem != null) // 增加空值检查
            {
                string selectedMaterialType = comboBox1.SelectedItem.ToString();
                if (!string.IsNullOrEmpty(selectedMaterialType))
                {
                    LoadDetailedTypes(selectedMaterialType);
                }
            }
        }

        private void material_select_Click(object sender, EventArgs e)
        {
            string materialType = comboBox1.SelectedItem?.ToString();
            string detailedType = comboBox2.SelectedItem?.ToString();
            int? materialId = null;
            if (!string.IsNullOrWhiteSpace(textBox1.Text) && int.TryParse(textBox1.Text, out int id))
            {
                materialId = id;
            }

            List<Model.Material> filteredMaterials = _materialBLL.SearchMaterials(materialType, detailedType, materialId);
            MaterialData.DataSource = filteredMaterials; // 确保这里绑定的是 List<Model.Material>
            SetDataGridViewColumnHeaders();
        }

        private void SetDataGridViewColumnHeaders()
        {
            MaterialData.Columns["MaterialId"].HeaderText = "物料ID";
            MaterialData.Columns["MaterialType"].HeaderText = "物料类型";
            MaterialData.Columns["DetailedMaterialType"].HeaderText = "详细类型";
            MaterialData.Columns["Quantity"].HeaderText = "数量";
            MaterialData.Columns["MaterialUnit"].HeaderText = "单位";
            MaterialData.Columns["MaterialDescription"].HeaderText = "描述";
            MaterialData.Columns["ConsumptionDeduction"].HeaderText = "消耗扣除";
            MaterialData.Columns["MaterialGroupNumber"].HeaderText = "物料组号";

            // 隐藏不需要的列
            MaterialData.Columns["ConsumptionDeduction"].Visible = false;
            MaterialData.Columns["MaterialGroupNumber"].Visible = false;
            if (MaterialData.Columns["History"] == null)
            {
                DataGridViewButtonColumn historyColumn = new DataGridViewButtonColumn
                {
                    Name = "History",
                    HeaderText = "历史记录",
                    Text = "查看历史",
                    UseColumnTextForButtonValue = true
                };
                MaterialData.Columns.Add(historyColumn);
            }
        }

        private void refreshButton_Click(object sender, EventArgs e)
        {
            // 清空 ComboBox1 和 ComboBox2 的选中项
            comboBox1.SelectedIndex = -1; // 清空选中项
            comboBox2.SelectedIndex = -1; // 清空选中项

            // 重新加载物料类型到 ComboBox1
            LoadMaterialTypes();

            // 重新加载所有材料到 DataGridView
            LoadMaterials();
        }

        private void CreMaterial_Click(object sender, EventArgs e)
        {
            // 打开 CreMaterial 窗体
            CreMaterial creMaterialForm = new CreMaterial();
            creMaterialForm.ShowDialog(); // 以模态方式打开窗体

            // 窗体关闭后，重新加载数据
            LoadMaterials();
        }

        private void MaterialData_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;

            // 检查是否点击了历史记录按钮列
            if (e.ColumnIndex == MaterialData.Columns["History"].Index)
            {
                try
                {
                    // 获取当前物料ID
                    int materialId = Convert.ToInt32(MaterialData.Rows[e.RowIndex].Cells["MaterialId"].Value);

                    // 获取该物料的更新历史记录
                    List<Model.Material.History> updateHistory = _materialBLL.GetMaterialHistory(materialId, "UPDATE");

                    // 创建或显示历史记录窗体
                    if (_historyForm == null || _historyForm.IsDisposed)
                    {
                        _historyForm = new HistoryForm();
                        _historyForm.FormClosed += (s, args) => _historyForm = null;
                    }

                    // 加载更新记录并显示窗体
                    _historyForm.LoadHistory(updateHistory, $"物料ID: {materialId} 的更新历史记录");
                    _historyForm.Show();
                    _historyForm.BringToFront();
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"加载历史记录失败: {ex.Message}", "错误",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        private void btnDelete_Click(object sender, EventArgs e)
        {
            // 检查是否有选中的行
            if (MaterialData.SelectedRows.Count == 0)
            {
                MessageBox.Show("请先选择要删除的物料！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 获取选中的行
            DataGridViewRow selectedRow = MaterialData.SelectedRows[0];
            int materialId = Convert.ToInt32(selectedRow.Cells["MaterialId"].Value);
            string materialName = selectedRow.Cells["MaterialDescription"].Value.ToString();

            // 确认删除对话框
            DialogResult result = MessageBox.Show($"确定要删除物料 '{materialName}' (ID: {materialId}) 吗？",
                                                  "确认删除",
                                                  MessageBoxButtons.YesNo,
                                                  MessageBoxIcon.Question);

            if (result == DialogResult.Yes)
            {
                try
                {
                    // 调用 BLL 删除方法
                    int rowsAffected = _materialBLL.DeleteMaterial(materialId);

                    if (rowsAffected > 0)
                    {
                        MessageBox.Show("物料删除成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        // 刷新数据
                        LoadMaterials();
                    }
                    else
                    {
                        MessageBox.Show("物料删除失败，请重试！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"删除物料时出错：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        private void btnEdit_Click(object sender, EventArgs e)
        {
            // 检查是否有选中的行
            if (MaterialData.SelectedRows.Count == 0)
            {
                MessageBox.Show("请先选择要修改的物料！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (MaterialData.SelectedRows.Count != 1)
            {
                MessageBox.Show("请选择且仅选择一行进行修改！", "提示",
                                MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 获取选中的行
            DataGridViewRow selectedRow = MaterialData.SelectedRows[0];
            int materialId = Convert.ToInt32(selectedRow.Cells["MaterialId"].Value);

            // 获取物料详细信息
            Model.Material selectedMaterial = _materialBLL.GetMaterialById(materialId);

            if (selectedMaterial == null)
            {
                MessageBox.Show("无法获取物料详细信息！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // 创建 UpMaterial 窗体实例
            UpMaterial upMaterialForm = new UpMaterial();

            // 将选中的物料信息填充到 UpMaterial 窗体的 TextBox 中
            upMaterialForm.txtMaterialType.Text = selectedMaterial.MaterialType;
            upMaterialForm.txtDetailedMaterialType.Text = selectedMaterial.DetailedMaterialType;
            upMaterialForm.txtQuantity.Text = selectedMaterial.Quantity?.ToString() ?? string.Empty;
            upMaterialForm.txtMaterialUnit.Text = selectedMaterial.MaterialUnit;
            upMaterialForm.txtMaterialDescription.Text = selectedMaterial.MaterialDescription;
            upMaterialForm.txtConsumptionDeduction.Text = selectedMaterial.ConsumptionDeduction;
            upMaterialForm.txtMaterialGroupNumber.Text = selectedMaterial.MaterialGroupNumber;

            // 将物料 ID 传递给 UpMaterial 窗体，用于后续的更新操作
            upMaterialForm.Tag = materialId;

            // 显示 UpMaterial 窗体
            upMaterialForm.ShowDialog();

            // 如果物料信息被修改，刷新物料数据
            if (upMaterialForm.DialogResult == DialogResult.OK)
            {
                LoadMaterials();
            }
        }
        private void BtnShowDeleted_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取所有删除记录
                List<Model.Material.History> deletedMaterials = _materialBLL.GetAllDeletedMaterials();

                // 创建或显示历史记录窗体
                if (_historyForm == null || _historyForm.IsDisposed)
                {
                    _historyForm = new HistoryForm();
                    _historyForm.FormClosed += (s, args) => _historyForm = null;
                }

                // 加载删除记录并显示窗体
                _historyForm.LoadHistory(deletedMaterials, "已删除物料历史记录");
                _historyForm.Show();
                _historyForm.BringToFront();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载删除记录失败: {ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

    }
}